import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

enum NetWorkState {
  Connected,
  Unable,
  NotLogin,
}

var networkStateMap = const {
  NetWorkState.Connected: "已连接",
  NetWorkState.NotLogin: "已连接，校园网未登录，正在重连中。。。",
  NetWorkState.Unable: "网络错误，未连接",
};

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'CAU校园网自动连接工具'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Timer _timer;
  final TextEditingController _nameControl = new TextEditingController();
  final TextEditingController _passwdControl = new TextEditingController();
  var _state = NetWorkState.Connected;
  var _icon = Icon(Icons.play_arrow_rounded);
  var _keepState = false;

  Future<NetWorkState> setNetWork() async {
    Future<NetWorkState> checkNetWork() async {
      var response;
      try {
        response = await Dio(BaseOptions(
          connectTimeout: 1000,
          receiveTimeout: 1000,
        )).get('http://www.baidu.com');
      } catch (e) {
        return NetWorkState.Unable;
      }
      if (response.realUri.toString() == "http://www.baidu.com") {
        return NetWorkState.Connected;
      } else {
        return NetWorkState.NotLogin;
      }
    }

    var state = await checkNetWork();
    if (state == NetWorkState.NotLogin) {
      var username = _nameControl.text;
      var passwd = _passwdControl.text;
      try {
        var _ = await Dio(BaseOptions(
          connectTimeout: 1000,
          receiveTimeout: 1000,
        )).get("http://10.3.191.9/drcom/login?callback=dr1003&DDDDD=$username%40cau&upass=$passwd&0MKKey=123456&R1=0&R3=0&R6=0&para=00&v6ip=&v=1574");
      } catch (e) {
        DateTime now = new DateTime.now();
        print("$now,登陆时网络错误！请检查网络连接是否正常！");
      }
      await Future.delayed(Duration(milliseconds: 500));
      state = await checkNetWork();
      DateTime now = new DateTime.now();
      if (state == NetWorkState.Connected) {
        print("$now,$username账户，校园网登陆成功！");
      } else {
        print("$now,登陆失败，请检查用户名和密码是否正确！");
      }
      return state;
    }
    return state;
  } // 检查网络状态

  void _switchKeepState() {
    void cancelTimer() {
      if (_timer != null) {
        _timer.cancel();
      }
    } // 取消计时器

    if (_keepState == false) {
      setState(() {
        _icon = Icon(Icons.stop_rounded);
        final Duration duration = Duration(seconds: 5);
        cancelTimer();

        _timer = Timer.periodic(duration, (timer) async {
          if (this.mounted) {
            var t = await setNetWork();
            setState(() {
              _state = t;
            });
          }
        });
      });
    } else {
      setState(() {
        _icon = Icon(Icons.play_arrow_rounded);
      });
      cancelTimer();
    }
    _keepState = !_keepState;
  } // 计时器切换状态

  void getUserPasswdFromPrefs() async {
    var prefs = await SharedPreferences.getInstance();
    _passwdControl.text = prefs.getString('passwd');
    _nameControl.text = prefs.getString('name');
  } // 从持久化储存读取配置

  void _onChanged(String t) async {
    void setUserPasswdToPrefs() async {
      var prefs = await SharedPreferences.getInstance();
      prefs.setString('passwd', _passwdControl.text);
      prefs.setString('name', _nameControl.text);
    } // 向持久化储存写入配置

    setUserPasswdToPrefs();
  } // 在文本框改变时向持久化储存写入配置

  @override
  Widget build(BuildContext context) {
    getUserPasswdFromPrefs();
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                labelText: '请输入你的学号',
              ),
              controller: _nameControl,
              autofocus: false,
              onChanged: _onChanged,
            ),
            TextField(
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                labelText: '请输入你的密码',
              ),
              controller: _passwdControl,
              autofocus: false,
              obscureText: true,
              onChanged: _onChanged,
            ),
            Text(
              '您目前的网络状态是:',
            ),
            Text(
              networkStateMap[_state],
              // NetWorkToString(_state),
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _switchKeepState,
        tooltip: '开始/暂停',
        child: _icon,
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
